<template>
<div class="app-container">
  <loading v-show="loading"></loading>
  <el-card class="box-card searchBox searchFormStyle" style="margin-bottom:1%;">
    <div slot="header" class="clearfix">
      <span>用户信息操作</span>
    </div>
    <div class="text item">
      <el-form :model="SearchDep" ref="SearchDep" label-width="130px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="用户账号">
              <el-input v-model="SearchDep.userAccount"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户姓名">
              <el-input v-model="SearchDep.userName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item>
              <el-button type="primary" 
              icon="el-icon-plus" 
              @click="openDialog">新 增</el-button>
              <el-button type="primary" 
              icon="el-icon-search" 
              @click="getList">查 询</el-button>
              <el-button type="primary" 
              icon="el-icon-refresh" 
              @click="resetSearch">重 置</el-button>
              <el-button type="info" 
              icon="el-icon-delete" 
              @click="deleteDepar">删 除</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </el-card>
  <el-card class="box-card" style="margin-bottom:1%;">
    <div slot="header" class="clearfix">
      <span>用户信息列表</span>
    </div>
    <el-table
      :data="tableData"
      ref="tableData"
      border
      style="width: 100%;margin-bottom:1%;"
      @selection-change="handleSelectionChange"
      >
      <el-table-column
        type="selection"
        width="40">
      </el-table-column>
      <el-table-column
        label="角色名"
      >
        <template slot-scope="scope">
            {{ scope.row.userAccount }}
        </template>
      </el-table-column>
      <el-table-column
        label="职称名"
       >
        <template slot-scope="scope">
            {{ scope.row.userName }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="390px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            icon="el-icon-document"
            @click="handleAuth(scope.$index, scope.row)">授权</el-button>
          <el-button
          <el-button
            size="mini"
            icon="el-icon-document"
            @click="handleDetail(scope.$index, scope.row)">详细</el-button>
          <el-button
            size="mini"
            icon="el-icon-edit-outline"
            @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button
            size="mini"
            icon="el-icon-delete"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange" :paginations="paginations"></pagination>
  </el-card>
  <!--新增角色开始-->
  <el-dialog  :title="dialogTitle" :visible.sync="dialogFormVisible" width="80%">
    <el-form :model="addForm" :rules="rules" ref="addForm" label-width="140px">
      <el-row>
          <el-col :span="8">
            <el-form-item label="角色名" prop="userAccount">
              <el-input v-model="addForm.userAccount" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="职称名" prop="userName">
              <el-input v-model="addForm.userName" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button  icon="el-icon-refresh"  @click="resetForm('addForm')">重置</el-button>
      <el-button  type="primary"  icon="el-icon-plus"  @click="submitForm('addForm')">保 存</el-button>
    </div>
  </el-dialog>
  <!--新增角色结束-->
  <!--角色详情开始-->
  <el-dialog :title="dialogTitle" :visible.sync="detailFormVisible" width="80%">
    <el-form :model="addForm" :rules="rules" :disabled="ifDisabled" ref="addForm" label-width="140px" class="detailStyle">
      <el-row>
          <el-col :span="8">
            <span class="labelSpan">
              角色名:
            </span>
            <span class="valueSpan">
              {{addForm.userAccount}}
            </span>
          </el-col>
          <el-col :span="8">
            <span class="labelSpan">
              职称名:
            </span>
            <span class="valueSpan">
              {{addForm.userName}}
            </span>
          </el-col>
          <el-col :span="8">
            <span class="labelSpan">
              联系电话:
            </span>
            <span class="valueSpan">
              {{addForm.phone}}
            </span>
          </el-col>
      </el-row>
    </el-form>
  </el-dialog>
  <!--角色详情开始-->
  <!--角色授权开始-->
  <el-dialog :title="dialogTitle" :visible.sync="authFormVisible" width="80%">
    <div>
      <el-tree
        :data="authorList"
        ref="tree"
        show-checkbox
        node-key="id"
        :default-expand-all="false"
        :default-checked-keys="checkdefault"
        :props="defaultProps">
      </el-tree>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="authSubmitSuccess">确 定</el-button>
    </div>
  </el-dialog>
  <!--角色授权开始-->
</div>
</template>
<script>
import Loading from '@/components/loading/loading'
import pagination from '@/components/pagination/index'
import { getUserList, userDetail, addUser, deleteUser } from '@/api/resource/user'
import { isvalidPhone, isvalidWord, isvalidRequire } from '@/utils/validate'
import { transform } from '@/utils/trans'
// 非空
var validateRequire = (rule, value, callback) => {
  if (!isvalidRequire(value)) {
    callback(new Error('请输入必填项'))
  } else {
    callback()
  }
}

// 手机号
var validPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入电话号码'))
  } else if (!isvalidPhone(value)) {
    callback(new Error('请输入正确的11位手机号码'))
  } else {
    callback()
  }
}

// 汉字跟字母
var validWord = (rule, value, callback) => {
  if (!value) {
    callback(new Error(''))
  } else if (!isvalidWord(value)) {
    callback(new Error('只能输入汉字或字母'))
  } else {
    callback()
  }
}
export default {
  components: {
    Loading,
    pagination
  },
  data() {
    this.permissionHandle = this.$permissionHandle
    return {
      tableData: [], // 列表数据
      deleteDepArry: [],
      dialogTitle: '',
      loading: false,
      totalNum: 0,
      authorList: [], // 授权列表
      SearchDep: {
        userName: '',
        userAccount: ''
      },
      paginations: {
        totalNum: 0,
        currentPage: 1,
        pageSize: 10
      },

      ifDisabled: false, // 禁用表单

      addForm: {// 新增角色数据
        userAccount: '',
        userName: ''
      },
      orgName: '',
      partyOrgName: '',
      dialogFormVisible: false, // 新增弹出框状态
      detailFormVisible: false, // 详情弹出框
      authFormVisible: false, // 授权弹出框
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      checkdefault: [], // 默认授权
      // 列表所选数据集合
      multipleSelection: [],
      rules: {
        userAccount: [
          { required: true, message: '请输入用户账号' },
          { message: '数据不能包含特殊字符', validator: validateRequire },
          { min: 1, max: 21, message: '长度在 1 到 21 个字符', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入用户姓名' },
          { min: 1, max: 21, message: '长度在 1 到 21 个字符' },
          { message: '用户姓名只能输入汉字或字母', validator: validWord }
        ],
        phone: [
          { required: true, message: '请输入联系电话' },
          { trigger: 'blur', validator: validPhone }
        ]
      }
    }
  },
  watch: {
  },
  created() {
    this.getList()
    const component = this
    document.onkeydown = function(e) {
      e.keyCode === 13 && component.getList()
    }
  },
  methods: {
    changeStart() {
      this.pickerOptionsStart = Object.assign({}, this.pickerOptionsStart, {
        disabledDate: (time) => {
          return time.getTime() > new Date(this.addForm.formalPartyDate).getTime()
        }
      })
    },
    changeEnd() {
      this.pickerOptionsEnd = Object.assign({}, this.pickerOptionsEnd, {
        disabledDate: (time) => {
          return time.getTime() < new Date(this.addForm.joinPartyDate).getTime() - 86400000
        }
      })
    },
    // 新增打开弹出框
    openDialog() {
      this.dialogFormVisible = true
      this.dialogTitle = '角色新增'
      this.addForm = {
        userKey: ''
      }
      this.ifDisabled = false
      this.getDetail('add')
    },
    handleEdit(index, row) {
      this.addForm = row
      this.getDetail('edit')
      console.log(row)
      this.ifDisabled = false
      this.dialogFormVisible = true
      this.dialogTitle = '用户修改'
    },
    handleDetail(index, row) {
      this.detailFormVisible = true
      this.dialogTitle = '用户详情'
      this.addForm = {
        userKey: row.userKey
      }
      this.getDetail('detail')
    },
    handleAuth(index, row) {
      this.authFormVisible = true
      this.dialogTitle = '用户授权'
    },
    // 角色授权成功
    authSubmitSuccess() {
      const auth = []
      this.$refs.tree.getHalfCheckedNodes().forEach(val => {
        auth.push(val.id)
      })

      this.$refs.tree.getCheckedNodes().forEach(val => {
        auth.push(val.id)
      })
      auth.forEach(idx => {
        this.data3.forEach(el => {
          // debugger
          if (el.pId === idx) {
            auth.push(el.id)
          }
        })
      })
      this.dialogAuthVisible = false
      console.log(auth)
      const data = {
        roleKey: this.roleId,
        resourceIds: auth
      }
      authRole(data).then(res => {
        this.openwarning('授权成功', 'success')
      })
    },
    // 用户列表
    getList() {
      this.loading = true
      return new Promise((resolve, reject) => {
        getUserList(this.SearchDep).then(response => {
          console.log(response.data)
          this.tableData = response.data.entity.items
          this.partyOrgPostList = response.data.partyOrgPost
          this.roleList = response.data.roleList
          this.orgData = transform(response.data.orgList, 'orgKey', 'parOrg', 'children')
          this.ISNOT = response.data.ISNOT
          this.paginations.totalNum = parseInt(response.data.entity.itemsTotalCount)
          resolve()
          this.loading = false
        }).catch(error => {
          this.loading = false
          reject(error)
        })
      })
    },

    // 用户编辑及用户新增参数等信息
    getDetail(parmater) {
      if (parmater === 'add') {
        console.log(this.addForm)
      }
      if (parmater === 'edit') {
        console.log(2)
      }
      if (parmater === 'detail') {
        console.log(3)
      }
      // return new Promise((resolve, reject) => {
      //   userDetail(this.addForm).then(response => {
      //     if (response.data.entity.partyOrgPost) {
      //       this.partyOrgPost = JSON.parse(response.data.entity.partyOrgPost)
      //       this.addForm.partyOrgPost = this.partyOrgPost
      //     }
      //     if (response.data.partyMemberInfo && response.data.partyMemberInfo.sysOrgPost) {
      //       this.sysOrgPost = JSON.parse(response.data.partyMemberInfo.sysOrgPost)
      //       this.addForm.sysOrgPost = this.sysOrgPost
      //     }
      //     response.data.userRoles.forEach(element => {
      //       this.roleIds.push(element.roleId)
      //     })
      //     this.addForm.roleId = this.roleIds
      //     this.orgData = transform(response.data.orgList, 'orgKey', 'parOrg', 'children')
      //     this.partyOrgData = transform(response.data.partyOrgList, 'partyOrgKey', 'parPartyOrgInfoKey', 'children')
      //     if (parmater === 'edit' || parmater === 'detail') {
      //       if (response.data.partyMemberInfo) {
      //         this.addForm = {
      //           userKey: response.data.entity.userKey,
      //           userAccount: response.data.entity.userAccount,
      //           userName: response.data.entity.userName,
      //           phone: response.data.entity.phone
      //         }
      //       } else {
      //         this.addForm = {
      //           userKey: response.data.entity.userKey,
      //           userAccount: response.data.entity.userAccount
      //         }
      //       }
      //       if (parmater === 'detail') {
      //         this.ifDisabled = true
      //         this.getNodes()
      //       }
      //       this.getNodes()
      //     } else {
      //       this.$refs['addForm'].resetFields()
      //       this.addForm = { isPartyMember: '002' }
      //     }
      //     this.loading = false
      //     resolve()
      //   }).catch(error => {
      //     this.loading = false
      //     reject(error)
      //   })
      // })
    },
    addData() {
      this.loading = true
      addUser(this.addForm).then(response => {
        this.getList()
        this.dialogFormVisible = false
        this.loading = false
        this.addForm.roleId = []
        this.addForm.partyOrgPost = []
      }).catch(error => {
        console.log(error)
        // this.addForm.partyOrgPost = JSON.parse(this.addForm.partyOrgPost)
        // this.addForm.roleId = JSON.parse(this.addForm.roleId)
        this.loading = false
      })
    },
    deleteDepar() {
      if (this.deleteDepArry.length) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteUser({ 'userKey': JSON.stringify(this.deleteDepArry) }).then(response => {
            this.loading = false
            this.getList()
            this.deleteDepArry = []
          }).catch(error => {
            this.loading = false
            this.deleteDepArry = []
            console.log(error)
          })
        }).catch(() => {
          this.deleteDepArry = []
          this.$refs.tableData.clearSelection()
          return
        })
      } else {
        this.$message({
          showClose: true,
          message: '请至少选择一条要删除的数据',
          type: 'warning'
        })
      }
    },

    handleDelete(index, row) {
      this.deleteDepArry = []
      this.deleteDepArry.push(row.userKey)
      this.deleteDepar()
    },
    handleSelectionChange(val) {
      this.deleteDepArry = []
      this.multipleSelection = val
      this.multipleSelection.forEach(element => {
        this.deleteDepArry.push(element.userKey)
      })
    },
    // 改变分页的时候查询数据
    handleSizeChange(val) {
      console.log(val)
      this.SearchDep.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      console.log(val)
      this.SearchDep.pageNum = val
      this.getList()
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.addForm)
          this.addData()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) { // 重置表单数据
      // this.dialogFormVisible = false
      this.$refs[formName].resetFields()
      this.addForm.userName = ''
      this.addForm.userAccount = ''
    },
    handleNodeClick(data) {
      this.parentOrgName = data.orgName
      this.SearchDep.orgKey = data.orgKey
    },
    resetSearch() {
      this.SearchDep.userName = ''
      this.SearchDep.userAccount = ''
      this.getList()
      this.getAll()
    }
  }
}
</script>
<style lang="scss" scoped>
  .el-col-8{height:60px;}
  .tree-input{
    position: relative;
    margin-bottom:0;
    .el-form-item__content{line-height: auto;}
  }
  .input-tree{
      width: 100%;
      .el-scrollbar__wrap{overflow: auto;}
    }
    .tree-select,.el-date-editor{width: 100%;}
</style>
